const SERVER_URL = "http://127.0.0.1:8081"; // 后端 API 地址
const BOT_AVATAR = "/assets/images/znkf.jpg"; // 机器人头像
const USER_AVATAR = wx.getStorageSync("avatar") || "/assets/images/avatar.png"; // 用户头像

Page({
  data: {
    messages: wx.getStorageSync("chatHistory") || [], // 读取本地存储的聊天记录
    inputValue: "",
    conversationId: "",
    chatId: "",
    isLoading: false, // AI 正在思考的状态
  },

  onLoad() {
    const avatar = wx.getStorageSync("avatar");
    if (avatar && !this.checkImageValid(avatar)) {
    wx.setStorageSync("avatar", "/assets/images/avatar.png");
  }
    const history = wx.getStorageSync("chatHistory") || [];
    this.setData({ messages: history.length > 0 ? history : [] }); // ✅ 确保为空时不恢复旧记录
    this.scrollToBottom();
},
checkImageValid(url) {
    return new Promise(resolve => {
      wx.getImageInfo({
        src: url,
        success: () => resolve(true),
        fail: () => resolve(false)
      })
    })
  },

  onInput(e) {
    this.setData({ inputValue: e.detail.value });
  },

  async sendMessage() {
    if (!this.data.inputValue.trim()) return;

    const userMessage = { 
      content: this.data.inputValue, 
      isUser: true, 
      avatar: USER_AVATAR 
    };

    this.setData({ 
      messages: [...this.data.messages, userMessage], 
      inputValue: "",
      isLoading: true,  // 设置加载状态
    });

    this.scrollToBottom(); // 发送消息后滚动到底部

    try {
      wx.request({
        url: `${SERVER_URL}/parent/coze/chat/start`,
        method: "POST",
        header: { "Content-Type": "application/json" },
        data: {
          question: userMessage.content,
          parentId: wx.getStorageSync("parentId"),
        },
        success: (res) => {
          console.log("发送消息返回：", res.data);
          if (res.data.code === 0 && res.data.data) {
            const { conversationId, chatId } = res.data.data;
            this.setData({ conversationId, chatId });
            this.checkMessageStatus(conversationId, chatId);
          } else {
            wx.showToast({ title: "发送失败", icon: "none" });
            this.setData({ isLoading: false });
          }
        },
        fail: (err) => {
          console.error("发送消息失败：", err);
          wx.showToast({ title: "网络错误", icon: "none" });
            this.setData({ isLoading: false });
        },
      });
    } catch (err) {
      console.error("错误：", err);
      wx.showToast({ title: "发送失败", icon: "none" });
      this.setData({ isLoading: false });
    }
  },

  async checkMessageStatus(conversationId, chatId) {
    const interval = setInterval(() => {
      wx.request({
        url: `${SERVER_URL}/parent/coze/chat/message`,
        method: "GET",
        header: { "Content-Type": "application/json" },
        data: {
          conversationId,
          chatId,
          parentId: wx.getStorageSync("parentId"),
        },
        success: (res) => {
          console.log("查询消息返回：", res.data);
          if (res.data.code === 0 && res.data.data) {
            const { content, status } = res.data.data;
            if (status !== "in_progress") {
              clearInterval(interval);
              this.setData({ isLoading: false });

              // 解析 JSON 或者 Markdown
              let formattedContent = this.formatResponse(content);

              const botMessage = { 
                content: formattedContent, 
                isUser: false, 
                avatar: BOT_AVATAR 
              };

              let newMessages = [...this.data.messages, botMessage];
              this.setData({ messages: newMessages });

              wx.setStorageSync("chatHistory", newMessages); // 存储消息记录
              this.scrollToBottom(); // 滚动到底部
            }
          }
        },
        fail: (err) => {
          console.error("查询消息失败：", err);
          wx.showToast({ title: "网络错误", icon: "none" });
          this.setData({ isLoading: false });
        },
      });
    }, 2000);
  },

 // 解析 AI 返回的 JSON 并格式化
formatResponse(content) {
    try {
      let jsonData = JSON.parse(content);
      if (Array.isArray(jsonData)) {
        let formattedText = jsonData.map(item => 
          `姓名：${item.姓名}, 年龄：${item.年龄}，性别：${item.性别}，\n` +
          `身份证号：${item.身份证号}，\n` +
          `学校：${item.学校}，班级：${item.班级}，\n` +
          `老师名字：${item.老师.姓名}，老师电话：${item.老师.电话}\n`
        ).join("\n");
        return formattedText;
      } else {
        return JSON.stringify(jsonData, null, 2);
      }
    } catch (e) {
      return content; // 不是 JSON，直接返回文本
    }
  }
,  
 
  // 滚动到底部
  scrollToBottom() {
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 99999,
        duration: 300
      });
    }, 300);
  }
});
